<?php

namespace App\Admin\Forms;

use App\Models\TongUser;
use App\Models\TongUserProfit;
use App\Models\TongUserWithdrawal;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\DB;

class AuditWithdrawal extends Form
{
    use LazyWidget;
    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        // dump($input);
        $info = TongUserWithdrawal::query()->where('id',$input['id'])->first();
        if($info['status']!=1){
            return $this
                ->response()
                ->warning('请勿重复审核');
        }
        $update_data = [
            'status'=>$input['status']
        ];
        if($input['status']==3){
            $update_data['desc'] = $input['desc'];
        }
        DB::beginTransaction();
        try {
            TongUserWithdrawal::query()->where('id',$input['id'])->update($update_data);
            //扣除用户金额
            if($update_data['status']==2){
                //增加用户的流水记录
                TongUserProfit::query()->create([
                   'u_id'=>$info['u_id'],
                    'money'=>-$info['money'],
                    'type'=>9,//钱包提现
                    'symbol'=>2,//支出
                    'status'=>1,
                    'remark'=>'余额提现'.-$info['money'].'元',
                    'befor_money'=>$info['money'],
                    'after_money'=>bcsub($info['money'],$info['money'],2),
                ]);
            }else{
                //如果审核拒绝的话吧用户的钱给加回去
                TongUser::query()->where('id',$info['u_id'])->increment('money',$info['money']);
            }
            DB::commit();
            return $this
                ->response()
                ->success('审核完成')
                ->refresh();
        }catch (\Exception $exception){
            DB::rollBack();
            return $this->response()->error($exception->getMessage())->refresh();;
        }
        // return $this->response()->error('Your error message.');

    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->hidden('id','id')->required();
        $this->radio('status','状态')
            ->when(3,function(Form $form){
                $this->textarea('desc','拒绝的原因')->rules('required_if:status,3',['status.required_if'=>'请输入拒绝的原因'])
                    ->setLabelClass(['asterisk'])
                    ->rows(5);
            })
            ->options(['2' => '通过', '3'=> '拒绝'])
            ->default('2');
    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function default()
    {
        return [
            'id'=>$this->payload['id'] ?? null,
        ];
    }
}
